#pragma once
#include <iostream>
#include "InetAddr.hpp"
#include<functional>
#include "Socket.hpp"
#include"Protocol.hpp"
using process_t = std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)>;
class IOService
{
public:
    IOService(process_t process):_process(process)
    {}
    void IOExcute(SockSPtr sock, InetAddr &addr)
    {
        string packagestreamqueue;
        while (1)
        {
            int n = sock->Recv(&packagestreamqueue);
            if (n > 0)
            {
                string jsonstr=Decode(packagestreamqueue);
                if(jsonstr!="")
                {
                    cout << "get:" << jsonstr << endl;
                    // 获取到完整的报文
                    auto req = Factory::BuildRequest();
                    req->Deserialize(jsonstr);
                    auto resp = _process(req);
                    string respjson;
                    resp->Serialize(&respjson);
                    respjson=Encode(respjson);
                    cout << "result:" << respjson << endl;
                    cout << "-----------------------" << endl;
                    sock->Send(respjson);
                }
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.Ip().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read %s error\n", addr.Ip().c_str());
                break;
            }
        }
       
    }
    ~IOService()
    {
    }

private:
    process_t _process;
};
